<template>
  <template v-if="showBtn">
    <!-- <span class="operate-btn" v-if="disType == '20'" @click="handleClick">
      {{ name }}</span
    > -->
    <lay-button
      v-if="!parseRenderSetting['prefix-icon']"
      v-bind="parseRenderSetting"
      :class="classes"
      @click="handleClick"
    >
      {{ title }}
    </lay-button>
    <!-- 如果是操作栏的按钮，按钮存在图标的 仅仅展示按钮图标，鼠标滑过展示按钮名称 -->
    <lay-tooltip
      v-if="parseRenderSetting['prefix-icon']"
      :content="title"
      :is-dark="isDark"
    >
      <lay-button
        v-if="parseRenderSetting['prefix-icon']"
        v-bind="parseRenderSetting"
        :class="classes"
        @click="handleClick"
        >&nbsp;&nbsp;
      </lay-button>
    </lay-tooltip>
  </template>
  <lay-layer
    v-model="showLayer"
    :title="title"
    :shade="false"
    :btn="action"
    :area="['50vw', '50vh']"
  >
    <p>接口值||多选值</p>
    <lay-textarea autosize v-model="formValue"></lay-textarea>
    <p>表格值</p>
    <lay-textarea v-model="tableRowValue"></lay-textarea>
  </lay-layer>
</template>

<script setup lang="ts">
import { ref, useAttrs, computed } from "vue";
// import { layer } from "@layui/layui-vue";
import {
  getCopyData,
  getFormData,
  handleBtnFun,
  handleBtnFunMoreData,
  setFormData,
} from "../../api/module/login";
import { useSystemStore } from "../../store/login";
import { useRouter, useRoute } from "vue-router";
import { renderSettingMap } from "./utils";
import { layer } from "@layui/layui-vue";
import { transformTemplate } from "../../utils/transform";
import { number } from "echarts";
import { isEmpty } from "../../utils";
import { omit } from "lodash-es";
import {
  getAppId
} from '@/utils/core'

const showLayer = ref(false);
const formValue = ref("");
const attr = useAttrs();
defineOptions({
  name: "DcodeButton",
});

const props = defineProps({
  /**
   * 按钮名称
   */
  name: {
    type: String,
    default: "",
  },
  /**
   * 二次按钮图标
   */
  iconType: {
    type: String,
    default: "",
  },
  /**
   * 按钮样式
   */
  iconClass: {
    type: String,
    default: "",
  },
  /**
   * 是否开启二次按钮
   */
  enableConfirm: {
    type: [String, Number],
    default: 0,
  },
  /**
   * 行内容
   */
  row: {
    type: Object,
    default: () => ({}),
  },
  /**
   * 弹窗内容
   */
  confirmContent: {
    type: String,
    default: "",
  },
  /**
   * 调用服务端方法前事件
   */
  //todo
  beforeInvoke: {
    type: String,
    default: "",
  },
  /**
   * 路由跳转前事件
   */
  beforeNav: {
    type: String,
    default: "",
  },
  //tableRef
  tableRef: {
    type: Object,
  },
  /**
   * 按钮动态控制显示事件
   */
  beforeDisplay: {
    type: String,
    default: "",
  },
  //页面id
  pageId: {
    type: String,
    default: "",
  },
  // 显示位置 字典：10工具栏|20操作栏|30表格超链接|50前端自定义
  disType: {
    type: String,
  },
  renderSetting: {
    type: String,
    default: "",
  },
  contentScript: {
    type: String,
    default: "",
  },
  // 显示序号
  orderId: {
    type: [Number],
    default: 0,
  },
  //按钮id
  id: {
    type: [Number, String],
    default: "",
  },
  //超链接列位置(服务端新增字段） 显示位置为30链接列时，可配置列名，配置后显示为超链接列
  linkColumn: {
    type: String,
    default: "",
  },
  // 开启链接，链接名称
  linkcolumnName: {
    type: String,
    default: "",
  },
  //按钮描述
  description: {
    type: String,
    default: "",
  },
  //按钮id
  selectedKeys: {
    type: [Number, String],
    default: "",
  },
  //按钮id
  selectedKey: {
    type: [Number, String],
    default: "",
  },
  tableData: {
    type: Array,
    default: () => [],
  },
});
const title = ref(props.name);
// const userInfoStore = useSystemStore();
const tableRowValue = JSON.stringify(props.row);
const { ctx } = getCurrentInstance();

///Invoke Data
const funcInvokeMoreData = async () => {
  const data = (props.selectedKeys || props.selectedKeys || [props.row.id]).map(
    (item) => {
      return {
        id: item,
      };
    },
  );
  const params = {
    funcCode: props.id,
    dataset: data,
  };
  beforeClick(params);
  const res = await handleBtnFunMoreData(params);
  if (res.code == "1000") {
    layer.msg(res.message.toString(), { time: 1000, icon: 1 });
  } else {
    layer.msg("出错啦，请稍后重试");
  }
};
///Invoke Data
const funcInvokeData = async (data = {}) => {
  const params = {
    funcCode: props.id,
    data,
    pageId: props.pageId,
    appId: getAppId(),
  };
  beforeClick(params);
  const res = await handleBtnFun(params);
  if (res.code == "1000") {
    layer.msg(res.message.toString(), { time: 1000, icon: 1 });
  } else {
    layer.msg("出错啦，请稍后重试");
  }
};
///获取表单数据
const funcGetFormData = async (type: string) => {
  const params = {
    clientMacro: JSON.stringify({
      treeKey: "",
      treeName: "",
      appId: getAppId(),
    }),
    funcCode: props.id,
    pageId: props.pageId,
  };
  beforeClick(params);
  let res = await getFormData(params);
  if (res.code == "1000") {
    layer.msg(res.message.toString());
  } else {
    layer.msg("出错啦，请稍后重试");
  }

  ///打开弹窗的时候调用的
  if (type == "open") {
    formValue.value = JSON.stringify(res.data);
  } else {
    ///关闭弹窗的时候用的
    showLayer.value = false;
  }
};
const router = useRouter();
const route = useRoute();
const emit = defineEmits(["reset"]);
const getrowState = computed(() => {
  return (
    (!props.row || isEmpty(props.row)) &&
    (!props.selectedKey || props.selectedKey?.length == 0) &&
    (!props.selectedKeys || props.selectedKeys?.length == 0)
  );
});
///按钮点击事件
const btnClickFun = (val) => {
  const btnEventObj = {
    "10": () => {},
    "11": async () => {
      funcInvokeData();
    },
    ///当前行的 需要和table交互 props.row应该是不存在的（按钮在工具栏上时）
    "12": async () => {
      if (getrowState.value) {
        layer.msg("您还未选择数据哦，请先选择操作的数据。");
      } else {
        const data = (
          props.selectedKeys ||
          props.selectedKeys || [props.row.id]
        ).map((item) => {
          return {
            id: item,
          };
        });
        funcInvokeData(data[0]);
      }
    },
    ///多选行数的 需要和table交互
    "13": async () => {
      if (getrowState.value) {
        layer.msg("您还未选择数据哦，请先选择操作的数据。");
      } else {
        funcInvokeMoreData();
      }
    },
    "20": async () => {
      showLayer.value = true;
      funcGetFormData("open");
    },
    "21": async () => {
      showLayer.value = true;
      funcGetFormData("open");
    },
    "25": async () => {
      showLayer.value = true;
      funcGetFormData("open");
    },
    "26": async () => {
      if (!props.row || isEmpty(props.row)) {
        layer.msg("您还未选择数据哦，请先选择操作的数据。");
      } else {
        funcInvokeData();
      }
      emit("reset");
    },
    "27": async () => {
      if (!props.row || isEmpty(props.row)) {
        layer.msg("您还未选择数据哦，请先选择操作的数据。");
      } else {
        funcInvokeMoreData();
      }
      emit("reset");
    },
    "28": async () => {
      funcInvokeData();
    },
    "29": async () => {
      funcInvokeData();
    },
    "31": async () => {
      const data = props.row;
      let res = await handleBtnFunMoreData({
        pageId: props.pageId,
        appId: getAppId(),
        funcCode: props.id,
        dataset: [
          {
            ...omit(data, "REFDATA"),
          },
        ],
      });
      if (res.code == "1000") {
        emit("reset");
      }
    },
    "41": async () => {
      var settingInfo = JSON.parse(props.renderSetting || "");
      const params = {
        path: `/compage/${attr.navAddress}`,
        query: {
          parentDataId: props.row?.[settingInfo.mainTableKey || "id"],
          isChild: true,
        },
      };
      beforeClick(params);
      router.push(params);
    },
    "42": () => {
      const params = {
        path: `/compage/${attr.navAddress}`,
        query: { isChild: true },
      };
      beforeClick(params);
      router.push(params);
    },
    "43": async () => {
      var settingInfo = JSON.parse(props.renderSetting || "");
      const params = { funcCode: props.id, data: { id: props.id } };
      beforeClick(params);
      let res = (await handleBtnFun(params)).data;
      if (res.__navCode) {
        const query = {
          path: `/compage/${res.__navCode}`,
          query: {
            parentDataId: attr?.[settingInfo.mainTableKey || "id"],
            isChild: true,
            originalDataId: res.__originalDataId,
          },
        };
        beforeClick(query);
        router.push(query);
      } else {
        const query = {
          path: `/compage/${attr.navAddress}`,
          query: {
            parentDataId: attr?.[settingInfo.mainTableKey || "id"],
            isChild: true,
          },
        };
        beforeClick(query);
        router.push(query);
      }

      // router.push()
    },
    "44": async () => {
      const params = { funcCode: props.id };
      beforeClick(params);
      let res = await handleBtnFun(params);
      // setTimeout(() => {
      window.open(res.data);
      // }, 2000);
    },
    defaule: () => {},
    // '27': async () =>{
    //   await handleBtnFunMoreData({ funcCode: attr.id, dataset: props.tableRef?.getCheckData() })
    //   emit('reset')
    // }
  };
  return btnEventObj[val] || btnEventObj["defaule"];
};
///跳转路由前的校验

///二次弹窗事件
const showEnableConfirm = (callback?: () => void) => {
  var settingInfo = JSON.parse(props.renderSetting || "");
  var layContent = "";
  ///弹窗内容设置 confirmContent
  if (
    settingInfo.confirmContent &&
    (!settingInfo.contentScript || settingInfo.contentScript.length == 0)
  ) {
    layContent = settingInfo.confirmContent.toString();
  } else if (
    settingInfo.contentScript &&
    settingInfo.contentScript.length > 0
  ) {
    // 自定义内容 contentScript
    const generateFunc = settingInfo.contentScript
      .toString()
      .replace(
        /^function\s+generate\s*\(\)\s*{\s*return\s*{([\s\S]*)};\s*}$/g,
        "$1",
      );
    const fn = new Function(`${generateFunc}; return generate`);
    layContent = fn()({ tableData: props.row });
  } else {
    layContent = "确定" + props.name + "吗?";
  }
  layer.confirm(layContent, {
    title: settingInfo.windowTitle || "提示",
    btn: [
      {
        text: "确定",
        callback: (id: any) => {
          layer.close(id);
          // toSubmit();
          if (callback) {
            callback();
          }
        },
      },
      {
        text: "取消",
        callback: (id: any) => {
          ///取消操作
          layer.close(id);
        },
      },
    ],
  });
};
///提交操作
const toSubmit = () => {};
//按钮操作前事件
const beforeClick = (params) => {
  var settingInfo = props.renderSetting
    ? JSON.parse(props.renderSetting || "")
    : {};
  // beforeRequestMethod 服务端方法请求前（涉及到服务端方法请求的） TODO
  if (
    settingInfo.beforeRequestMethod &&
    settingInfo.beforeRequestMethod.length > 0
  ) {
    // 自定义内容 beforeRequestMethod
    const vueThis = { ...ctx, $route: route, $router: router };
    const generateFunc = settingInfo.beforeRequestMethod
      .toString()
      .replace(
        /^function\s+generate\s*\(\)\s*{\s*return\s*{([\s\S]*)};\s*}$/g,
        "$1",
      );
    const fn = new Function(`${generateFunc}; return generate`);
    // try {
    fn()({ param: params, instance: vueThis, btn: { ...props } });
    // } catch (error) {}
    // 调用示例  fn()({ param: {"routeid":''},instance:window });
    // console.log(fn()({ param: {"routeid":''},instance:window }));
  }
  ///页面跳转前（跳转类按钮） beforeNavScript TODO
  if (
    settingInfo.beforeNavScript &&
    settingInfo.beforeNavScript.length > 0 &&
    [40, 41, 42, 43, 44].includes(Number(attr.btnType))
  ) {
    const generateFunc = settingInfo.beforeNavScript
      .toString()
      .replace(
        /^function\s+generate\s*\(\)\s*{\s*return\s*{([\s\S]*)};\s*}$/g,
        "$1",
      );
    const vueThis = { ...ctx, $route: route, $router: router };
    const fn = new Function(`${generateFunc}; return generate`);
    try {
      fn()({ param: params, instance: vueThis, btn: { ...props } });
    } catch (error) {}
    // 调用示例  fn()({ param: {"query":{"isScan":''}},instance:window });
    // console.log( fn()({ param: {"query":{"isScan":''}},instance:window }));
    // query参数名以cm_开头会加到客户端宏变量中  TODO
  }
};

///点击按钮事件
const handleClick = () => {
  var settingInfo = props.renderSetting
    ? JSON.parse(props.renderSetting || "")
    : {};

  ///弹窗标题自定义（弹窗类按钮） TODO
  if (settingInfo.windowTitle && settingInfo.windowTitle.length > 0) {
    title.value = settingInfo.windowTitle;
  }
  ///自定义主键（弹窗类\跳转类按钮） TODO
  if (settingInfo.mainTableKey && settingInfo.mainTableKey.length > 0) {
    // console.log(settingInfo.mainTableKey, "mainTableKey");
  }
  ///如果有二次弹窗 优先处理二次弹窗，在处理后面的事件
  if (settingInfo["enableConfirm"] && settingInfo["enableConfirm"] == 1) {
    showEnableConfirm(btnClickFun(attr.btnType));
  } else {
    btnClickFun(attr.btnType)();
  }

  // try {
  // eslint-disable-next-line no-empty
  // } catch (error) {}
  //todo
  /**
   * 执行点击事件
   */
};
const showBtn = ref(true);
const action = ref([
  {
    text: "确认",
    callback: async () => {
      if (
        attr.btnType == "20" ||
        attr.btnType == "21" ||
        attr.btnType == "22" ||
        attr.btnType == "29"
      ) {
        funcSetFormData();
      } else if (attr.btnType == "28") {
        funcGetFormData("close");
      }
    },
  },
  {
    text: "取消",
    callback: () => {
      showLayer.value = false;
    },
  },
]);
///存储表单方法
const funcSetFormData = async () => {
  const params = {
    data: {
      address: "test",
      code: "1111",
      nianyue: null,
      zgfz: "",
      name: "张三",
      signed: 1,
      state: 2,
      id: "1114638255497678848",
      age: 13,
      _submit: true,
      _formKey: "",
    },
    funcCode: props.id,
    pageId: props.pageId,
  };
  beforeClick(params);
  let res = await setFormData(params);
  if (res.code == "1000") {
    layer.msg(res.message.toString());
    showLayer.value = !showLayer.value;
  } else {
    layer.msg("出错啦，请稍后重试");
  }
};
///复制数据方法
const funcGetCopyData = async () => {
  const params = {
    clientMacro: '{"treeKey":"","treeName":"","appId":"673605666534854656"}',
    id: "718931156858310656", ///id是否指pageId 二期待确认
    funcCode: props.id,
    pageId: props.pageId,
  };
  beforeClick(params);
  let res = await getCopyData();
  if (res.code == "1000") {
    layer.msg(res.message.toString());
    showLayer.value = !showLayer.value;
  } else {
    layer.msg("出错啦，请稍后重试");
  }
};
///按钮type的展示
const parseRenderSetting = computed(() => {
  return props.renderSetting
    ? Object.entries(JSON.parse(props.renderSetting || "")).reduce(
        (pre, [key, value]) => {
          pre[renderSettingMap.get(key) ?? ""] = value;
          return pre;
        },
        {},
      )
    : {};
});

const classes = computed(() => {
  return [(props.disType === "20" || props.disType === "30") && "operate-btn"];
});
onMounted(() => {
  if (props.linkColumn && props.linkColumn.length > 0) {
    title.value = props.linkcolumnName;
  }
  ///判断是否展示按钮组件
  if (props?.renderSetting && props.renderSetting != null) {
    var settingInfo = JSON.parse(props?.renderSetting || "");
    if (
      settingInfo["displayScript"] != null &&
      settingInfo["displayScript"].length > 0
    ) {
      const generateFunc = settingInfo["displayScript"]
        .toString()
        .replace(
          /^function\s+generate\s*\(\)\s*{\s*return\s*{([\s\S]*)};\s*}$/g,
          "$1",
        );
      const fn = new Function(`${generateFunc}; return generate`);
      showBtn.value = fn()({ tableData: props.row });
    }
  }
});
</script>

<style scoped lang="less">
.operate-btn {
  border: none;
  cursor: pointer;
  color: #1e9fff;
  padding: 0 8px;
}
</style>
